package com.bootdo.order.task;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bootdo.cash.dao.CashDao;
import com.bootdo.cash.domain.CashDO;
import com.bootdo.common.utils.ExceptionUtils;
import com.bootdo.essential.dao.BankDao;
import com.bootdo.essential.domain.BankDO;
import com.bootdo.merchant.domain.MerchantDO;
import com.bootdo.order.domain.OrderPayDO;
import com.bootdo.quota.dao.QuotaDao;
import com.bootdo.quota.domain.QuotaDO;

public class LowerTask implements Runnable  {

    private static final Logger logger = LoggerFactory.getLogger(LowerTask.class);

    private MerchantDO merchant;
    private OrderPayDO orderPay;
    private BankDao bankMapper;
    private QuotaDao quotaMapper;
    private CashDao cashMapper;

    public LowerTask(MerchantDO merchant, OrderPayDO orderPay, BankDao bankMapper, QuotaDao quotaMapper, CashDao cashMapper){
        this.merchant = merchant;
        this.orderPay = orderPay;
        this.bankMapper = bankMapper;
        this.quotaMapper = quotaMapper;
        this.cashMapper = cashMapper;
    }

    @Override
    public void run() {
        //获取商户默认收款账号
        try {
            BankDO bank = bankMapper.getByUser(merchant.getUserId());
            if (bank != null){
                double moneys = 0.00;
                QuotaDO quota = quotaMapper.get(merchant.getUserId());
                if (quota != null){
                    moneys = quota.getActualQuota();
                }
                //获取当前商户已申请提现金额
                double m = cashMapper.findMoneyCount(merchant.getUserId());
                double countMoney = moneys + orderPay.getOrderMoney() - orderPay.getCountMoney() - m;
                //新增默认提现
                CashDO cash = new CashDO();
                cash.setUserId(merchant.getUserId());
                cash.setCashMoney(countMoney);
                cash.setBankId(bank.getId());
                cash.setStatus(0);
                cash.setGmtCreate(new Date());
                cashMapper.save(cash);
            }
        } catch (Exception e) {
            logger.error("<============调用线程自动下发失败============>：" + merchant.getUserId() + "，失败原型"+ ExceptionUtils.getStackTraceAsString(e));
        } finally {
            bankMapper = null;
            quotaMapper = null;
            cashMapper = null;
        }
    }
}
